layui.config({
    base: "../../js/"
}).extend({
    "utilObj": "utilObj"
})
layui.use(['utilObj', 'form', 'layer', 'laydate', 'table', 'laytpl', 'laypage', 'util'], function () {
    var utilObj = layui.utilObj;//自定义模块，包含ajax
    var laypage = layui.laypage;
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;
    //用户每日登陆 和每日活跃用户数不同
    var pageSummarUrl = "/cms/report/getPageSummary";
    var buttonClickUrl = "/cms/report/getButtonClickRank";
    var pagePage = {
        getData: function () {
            pagePage.getPageSummary();
            pagePage.getButtonClickSummary();
        },
        getPageSummary: function () {
            var startTime = $("#startTime").val();
            var endTime = $("#endTime").val();
            utilObj.showLoading();
            utilObj.ajax({
                url: pageSummarUrl,
                data: {
                    startDate: startTime,
                    endDate: endTime
                },
                success: function (data) {
                    console.log(data);
                    if (data) {
                        pagePage.bindPagePvUv(data);
                        pagePage.bindBounceRate(data);
                        pagePage.bindPageTime(data);
                        pagePage.renderPageSummary(data);
                    }
                    utilObj.hideLoading();
                },
                error: function (err) {
                    layer.msg(err.message);
                    utilObj.hideLoading();
                }
            });
        },
        getButtonClickSummary: function () {
            var startTime = $("#startTime").val();
            var endTime = $("#endTime").val();
            utilObj.showLoading();
            utilObj.ajax({
                url: buttonClickUrl,
                data: {
                    startDate: startTime,
                    endDate: endTime
                },
                success: function (data) {
                    console.log(data);
                    if (data) {
                        pagePage.bindButtonClick(data);
                        pagePage.renderButtonClick(data);
                    }
                    utilObj.hideLoading();
                },
                error: function (err) {
                    layer.msg(err.message);
                    utilObj.hideLoading();
                }
            });
        },
        //两条线数据
        bindPagePvUv: function (chartData) {
            if (chartData && chartData.length) {

            } else {

            }
            // 获取 CSV 数据并初始化图表
            var xData = [];
            var yData = [];
            var yDataPv = {
                name: '访问量PV',
                data: []
            };
            var yDataUv = {
                name: '访问量UV',
                data: []
            };
            for (var index in chartData) {
                xData.push(chartData[index].pageName);
                yDataPv.data.push(chartData[index].pageView);
                yDataUv.data.push(chartData[index].uniqueVisit);
            }
            yData.push(yDataPv);
            yData.push(yDataUv);
            var chart = Highcharts.chart('pagePvUv', {
                credits: {
                    enabled: false
                },
                legend: {
                    enabled: false
                },
                chart: {
                    type: 'line'
                },
                title: {
                    text: null
                },
                subtitle: {
                    text: null
                },
                xAxis: {
                    categories: xData,
                    labels: {
                        rotation: -90  // 设置轴标签旋转角度
                    }
                },
                yAxis: [{
                    title: {
                        text: 'PV'
                    }
                }, {
                    opposite: true,  // 通过此参数设置坐标轴显示在对立面
                    title: {
                        text: 'UV'
                    }
                }],
                tooltip: {
                    shared: true
                },
                plotOptions: {
                    line: {
                        dataLabels: {
                            // 开启数据标签
                            enabled: true
                        }
                    }
                },
                series: [
                    {
                        name: yDataPv.name,
                        data: yDataPv.data,
                        yAxis: 0
                    },
                    {
                        name: yDataUv.name,
                        data: yDataUv.data,
                        yAxis: 1
                    }
                ]
            });
        },
        bindPageTime: function (chartData) {
            if (chartData && chartData.length) {

            } else {

            }
            var xData = [];
            var yData = [];
            var yDataTotal = {
                name: '总时间',
                data: []
            };
            var yDataAva = {
                name: '平均时间',
                data: []
            };
            for (var index in chartData) {
                xData.push(chartData[index].pageName);
                yDataTotal.data.push(timeToSec(chartData[index].totalTime));
                yDataAva.data.push(timeToSec(chartData[index].averageTime));
            }
            yData.push(yDataTotal);
            yData.push(yDataAva);
            console.log(yData);
            Highcharts.chart('pageTime', {
                credits: {
                    enabled: false
                },
                legend: {
                    enabled: false
                },
                chart: {
                    type: 'line'
                },
                title: {
                    text: ""
                },
                subtitle: {
                    text: ""
                },
                xAxis: {
                    categories: xData,
                    labels: {
                        rotation: -90  // 设置轴标签旋转角度
                    }
                },
                yAxis: [{
                    title: {
                        text: '总时间(s)'
                    }
                }, {
                    opposite: true,  // 通过此参数设置坐标轴显示在对立面
                    title: {
                        text: '平均访问时间(s)'
                    }
                }],
                tooltip: {
                    shared: true
                },
                plotOptions: {
                    line: {
                        dataLabels: {
                            // 开启数据标签
                            enabled: true,
                            allowOverlap: true
                        }
                    }
                },
                series: [
                    {
                        name: yDataTotal.name,
                        data: yDataTotal.data,
                        yAxis: 0
                    },
                    {
                        name: yDataAva.name,
                        data: yDataAva.data,
                        yAxis: 1
                    }
                ]
            });
        },
        bindBounceRate: function (chartData) {
            // pageBrounceRate
            var lineData = [];
            for (var index in chartData) {
                if (index >= 10) {
                    break;
                }
                var items = [];
                items.push(chartData[index].pageName);
                items.push(chartData[index].bounceRate);
                lineData.push(items);
            }
            var chart = Highcharts.chart('pageBrounceRate', {
                credits: {
                    enabled: false
                },
                legend: {
                    enabled: false
                },
                chart: {
                    type: 'column'
                },
                title: {
                    text: null
                },
                subtitle: {
                    text: ''
                },
                xAxis: {
                    type: 'category',
                    labels: {
                        rotation: -90  // 设置轴标签旋转角度
                    }
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: '跳出率(%)'
                    }
                },
                legend: {
                    enabled: false
                },
                tooltip: {
                    pointFormat: '页面跳出率: <b>{point.y:.2f} %</b>'
                },
                series: [{
                    name: '跳出率',
                    data: lineData,
                    dataLabels: {
                        enabled: true,
                        rotation: -90,
                        color: '#FFFFFF',
                        align: 'right',
                        format: '{point.y:.2f}', // :.1f 为保留 1 位小数
                        y: 10
                    }
                }]
            });
        },
        bindButtonClick: function (chartData) {
            var lineData = [];
            for (var index in chartData) {
                if (index >= 10) {
                    break;
                }
                var items = [];
                items.push(chartData[index].buttonName);
                items.push(chartData[index].clickTimes);
                lineData.push(items);
            }
            Highcharts.chart('buttonClickRank', {
                credits: {
                    enabled: false
                },
                legend: {
                    enabled: false
                },
                chart: {
                    type: 'column'
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: ''
                },
                xAxis: {
                    type: 'category',
                    labels: {
                        rotation: -90  // 设置轴标签旋转角度
                    }
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: '点击次数'
                    }
                },
                tooltip: {
                    pointFormat: '按钮点击: <b>{point.y:.0f} 次</b>'
                },
                series: [{
                    name: '按钮点击',
                    data: lineData,
                    dataLabels: {
                        enabled: true,
                        rotation: -90,
                        color: '#FFFFFF',
                        align: 'right',
                        format: '{point.y:.0f}', // :.1f 为保留 1 位小数
                        y: 10
                    }
                }]
            });
        },
        renderPageSummary: function (data) {
            if (data && data.length) {
                $(".pagelist-content").show();
            } else {
                $(".pagelist-content").hide();
            }
            table.render({
                elem: '#pagePvUvList',
                cellMinWidth: 95,
                page: true,
                height: 315,
                limit: 7,
                id: 'pagePvUvListTable',
                cols: [[
                    {
                        field: 'pageName',
                        title: '页面名称',
                        minWidth: 100,
                        align: "center"
                    },
                    {
                        field: 'pageView',
                        title: '访问量',
                        minWidth: 100,
                        align: "center"
                    },
                    {
                        field: 'uniqueVisit',
                        title: '独立访客',
                        minWidth: 100,
                        align: "center"
                    },
                    {
                        field: 'bounceRate',
                        title: '跳出率',
                        minWidth: 100,
                        align: "center"
                    },
                    {
                        field: 'totalTime',
                        title: '访问总时间',
                        minWidth: 100,
                        align: "center"
                    },
                    {
                        field: 'averageTime',
                        title: '平均访问时间',
                        minWidth: 80,
                        align: 'center'
                    }
                ]],
                data: data
            });
        },
        renderButtonClick: function (data) {
            if (data && data.length) {
                $(".buttonlist-content").show();
            } else {
                $(".buttonlist-content").hide();
            }
            table.render({
                elem: '#buttonClickList',
                cellMinWidth: 95,
                page: true,
                height: 315,
                limit: 7,
                id: 'buttonClickListTable',
                cols: [[
                    {
                        field: 'buttonName',
                        title: '按钮名称',
                        minWidth: 100,
                        align: "center"
                    },
                    {
                        field: 'clickTimes',
                        title: '点击次数',
                        minWidth: 100,
                        align: "center"
                    }
                ]],
                data: data
            });
        },
        init: function () {
            Date.prototype.format = function (format) {
                var o = {
                    "M+": this.getMonth() + 1,
                    "d+": this.getDate(),
                    "h+": this.getHours(),
                    "m+": this.getMinutes(),
                    "s+": this.getSeconds(),
                    "q+": Math.floor((this.getMonth() + 3) / 3),
                    "S": this.getMilliseconds()
                }
                if (/(y+)/.test(format)) {
                    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(format)) {
                        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                    }
                }
                return format;
            }


            Highcharts.setOptions({
                colors: ['#BDA990', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
            });
            var today = new Date();
            var endDate = today;
            var startDate = new Date();
            var year = endDate.getFullYear() - 1;
            startDate.setYear(year);

            var startStr = startDate.format("yyyy-MM-dd").toString();
            var endStr = endDate.format("yyyy-MM-dd").toString();
            laydate.render({
                elem: '#startTime',
                type: 'date',
                value: startStr

            });
            laydate.render({
                elem: '#endTime',
                type: 'date',
                value: endStr
            });
            pagePage.getData();
        }
        ,
    };
    pagePage.init();

    var timeToSec = function (time) {
        var s = 0;
        if (time) {
            var hour = time.split(':')[0] ? time.split(':')[0] : 0;
            var min = time.split(':')[1] ? time.split(':')[1] : 0;
            var sec = time.split(':')[2] ? time.split(':')[2] : 0;
            s = Number(hour * 3600) + Number(min * 60) + Number(sec);
        }
        return s;
    };


    $(".confirm_btn").on("click", function () {
        pagePage.getData(1);
    });

})